package com.wxproject.demo.Common.exception;

import com.wxproject.demo.Common.MyException.BusinessException;
import com.wxproject.demo.Common.lang.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AccountException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zqf
 * @date 2021/3/31 19:14
 * @description
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBody handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常");
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultBody.error().message(objectError.getDefaultMessage());
    }

    //捕捉自定义异常
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResultBody bus(BusinessException e) {
        return ResultBody.error().message(e.getErrMsg()).code(e.getCode());
    }

    //捕捉 CustomRealm 抛出的异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(AccountException.class)
    public ResultBody handleShiroException(Exception ex) {
        return ResultBody.error().code(401).message(ex.getMessage());
    }
}
